import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions, ProFormCheckbox,
    ProFormText,
    ProFormTextArea,
    ProTable,
    ProFormDateRangePicker, ProFormDigit, ProFormUploadButton, ProFormSelect,
} from '@ant-design/pro-components';
import {Button, Drawer, Input, message, Modal, Tag, Badge, Space, Statistic} from 'antd';
import React, {useRef, useState} from 'react';
import type {DataCenterListItem} from './data';
import {dataCenterList, dataCenterAdd, dataCenterEdit, dataCenterDelete} from './service';
import {authorityList, userSelectList} from "@/pages/organization/user-list/service";

const {confirm} = Modal;
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: DataCenterListItem) => {
    const hide = message.loading('正在添加');

    try {
        await dataCenterAdd({...fields});
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};
/**
 * 更新节点
 *
 * @param fields
 */

export type FormValueType = {
    target?: string;
    template?: string;
    type?: string;
    time?: string;
    frequency?: string;
} & Partial<DataCenterListItem>;


const handleUpdate = async (fields: FormValueType, currentRow?: DataCenterListItem) => {
    const hide = message.loading('正在配置');

    try {
        await dataCenterEdit({
            ...currentRow,
            ...fields,
        });
        hide();
        message.success('配置成功');
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};


/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: DataCenterListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
        await dataCenterDelete({
            dataCenterIds: selectedRows.map((row) => row.dataCenterId),
        });
        hide();
        message.success('删除成功，即将刷新');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const DataCenterList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /** 分布更新窗口的弹窗 */
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<DataCenterListItem>();
    const [selectedRowsState, setSelectedRows] = useState<DataCenterListItem[]>([]);
    /** 国际化配置 */
    const columns: ProColumns<DataCenterListItem>[] = [
        {
            title: '资源池ID',
            dataIndex: 'dataCenterId',
            search: false,
            hidden: true,
        },
        {
            title: '资源池名称',
            dataIndex: 'name',
            search: true,
        },
        {
            title: '主机前缀',
            dataIndex: 'hostComputerPrefix',
            search: false,
        },
        {
            title: '主机',
            dataIndex: 'hostComputer',
            search: false,
            render: (value, record, index) => {
                return `${record.sellNum.toString()} / ${record.peerNum.toString()}`;
            },
        },
        {
            title: '管理员',
            // dataIndex: 'admin',
            dataIndex: ['admin', 'username'],
            search: false,
        },
        {
            title: '状态',
            dataIndex: 'status',
            search: false,
            // @ts-ignore
            tip: '黄色为告警信息，红色为异常信息',
            render: (value, record, index) => {
                return <Space>
                    <Badge count={record.status.warning} showZero color="#faad14"/>
                    <Badge count={record.status.fatal}/>
                </Space>;
            },
        },
        {
            title: '监控地址',
            dataIndex: 'monitorAddr',
            valueType: 'text',
            search: false,
        },
        {
            title: '描述',
            dataIndex: 'description',
            valueType: 'text',
            search: false,
            hidden: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => {
                return [
                    <a
                        key="config"
                        onClick={() => {
                            handleUpdateModalVisible(true);
                            setCurrentRow(record);
                        }}
                    >
                        编辑
                    </a>,
                ]
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<DataCenterListItem, API.ListPagination>
                headerTitle="资源池列表"
                actionRef={actionRef}
                rowKey="dataCenterId"
                search={{
                    labelWidth: 90,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined/> 新建
                    </Button>,
                ]}
                request={dataCenterList}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
                options={{
                    density: true,
                    fullScreen: true,
                    reload:true,
                    setting: false
                }}
                expandable={{
                    expandedRowRender: (record) => <p style={{marginLeft: 80}}>{record.description}</p>,
                    rowExpandable: (record) => record.description !== '',
                }}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            confirm({
                                title: '删除资源池',
                                // icon: <ExclamationCircleFilled />,
                                content: '删除资源池前，请确认资源池下主机等资源已清除，是否现在删除?',
                                onOk() {
                                    handleRemove(selectedRowsState);
                                    setSelectedRows([]);
                                    actionRef.current?.reloadAndRest?.();
                                    return true;
                                }
                            });
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}

            <ModalForm
                title="添加资源池"
                width="550px"
                open={createModalVisible}
                onVisibleChange={handleModalVisible}
                onFinish={async (value) => {
                    const success = await handleAdd(value as DataCenterListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}

            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '资源池名称为必填项',
                        },
                    ]}
                    // width="md"
                    name="name"
                    label="资源池名称"
                />
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '资源池主机前缀',
                        },
                    ]}
                    // width="md"
                    name="hostComputerPrefix"
                    label="资源池主机前缀"
                />
                <ProFormSelect
                    label="管理员"
                    name="adminId"
                    style={{width: 200}}
                    request={async () => {
                        const res = await userSelectList({organizationId: "1"});
                        return res.data.map((item) => ({
                            label: item.username,
                            value: item.userid,
                        }));
                    }}
                    placeholder="请选择角色"
                    rules={[{required: true, message: '请选择角色'}]}
                />

                <ProFormText
                    // width="md"
                    name="monitorAddr"
                    label="监控地址"
                />

                <ProFormTextArea
                    // width="md"
                    name="description"
                    label="资源池简介"

                />
            </ModalForm>
            <ModalForm
                title="编辑资源池信息"
                width="550px"
                open={updateModalVisible}
                onVisibleChange={handleUpdateModalVisible}
                onFinish={async (value) => {
                    const success = await handleUpdate(value, currentRow);
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                modalProps={{destroyOnClose: true}}
                initialValues={{
                    name: currentRow?.name,
                    adminId: currentRow?.admin?.userid,
                    connAddr: currentRow?.connAddr,
                    monitorAddr: currentRow?.monitorAddr,
                    description: currentRow?.description,
                    hostComputerPrefix: currentRow?.hostComputerPrefix,
                }}
            >
                <ProFormText
                    rules={[
                        {
                            required: true,
                            message: '资源池名称为必填项',
                        },
                    ]}
                    fieldProps={{disabled: true}}
                    width="md"
                    name="name"
                    label="资源池名称"
                />
                <ProFormText
                    fieldProps={{disabled: true}}
                    width="md"
                    name="hostComputerPrefix"
                    label="资源池主机前缀"
                />
                <ProFormSelect
                    label="管理员"
                    name="adminId"
                    style={{width: 200}}
                    request={async () => {
                        const res = await userSelectList({organizationId: "1"});
                        return res.data.map((item) => ({
                            label: item.username,
                            value: item.userid,
                        }));
                    }}
                    placeholder="请选择管理员"
                    rules={[{required: true, message: '请选择管理员'}]}
                />

                <ProFormText
                    // width="md"
                    name="monitorAddr"
                    label="监控地址"
                />

                <ProFormTextArea
                    // width="md"
                    name="description"
                    label="资源池简介"
                />
            </ModalForm>
        </PageContainer>
    );
};

export default DataCenterList;
